package com.ktmall.ktmalluijava.controller;

import com.ktmall.ktmalluijava.mapper.GoodsMapper;
import com.ktmall.ktmalluijava.pojo.Goods;
import com.ktmall.ktmalluijava.service.GoodsService;
import com.ktmall.ktmalluijava.utils.Page;
import com.ktmall.ktmalluijava.utils.ResMsg;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/5/16 上午11:36
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;

    @GetMapping("/list")
    public String select(String name, Integer brandId, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "5") Integer pageSize) {
        Page<Goods> page = goodsService.getPage(name, brandId, pageNo, pageSize);
        return ResMsg.success("商品列表加载成功", page);
    }

    @PostMapping("/add")
    public String add(@RequestBody Goods goods) {
        int i = goodsService.add(goods);
        if (i > 0) {
            return ResMsg.success("新增成功");
        } else {
            return ResMsg.error("新增失败");
        }
    }

    @GetMapping("/detail")
    public String detail(Integer id) {
        Goods goods;
        try {
            goods = goodsService.detail(id);
        } catch (Exception e) {
            return ResMsg.error("商品详情加载失败", e);
        }
        return ResMsg.success("商品详情加载成功", goods);
    }

    @PostMapping("/update")
    public String update(@RequestBody Goods goods) {
        int i = goodsService.update(goods);
        if (i > 0) {
            return ResMsg.success("修改成功");
        } else {
            return ResMsg.error("修改失败");
        }
    }

    @PostMapping("/del")
    public String delete(@RequestBody Integer... id) {
        int i = goodsService.delete(id);
        if (i > 0) {
            return ResMsg.success("删除成功");
        } else {
            return ResMsg.error("删除失败");
        }
    }

    @GetMapping("/all")
    public String getAll(){
        return ResMsg.success("所有商品列表加载成功",goodsService.getAll());
    }

}
